package com.aiboleepro.handler;

import com.aiboleepro.base.BaseException;
import com.aiboleepro.constant.ErrorCode;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * http错误处理器
 * 将容器错误抛到controller层面
 *
 * @author aiboleepro
 * @date 2018-08-29 下午11:10
 **/
@RestController
public class HttpErrorHandler implements ErrorController {

    private static final String PATH = "/error";

    @Resource
    private ErrorAttributes errorAttributes;

    @Override
    public String getErrorPath() {
        return PATH;
    }

    @RequestMapping(value = PATH, produces = {MediaType.APPLICATION_JSON_VALUE})
    public void error(HttpServletRequest request) {
        ServletWebRequest servletWebRequest = new ServletWebRequest(request);
        Map<String, Object> errorAttributes = this.errorAttributes.getErrorAttributes(servletWebRequest, true);
        String path = (String) errorAttributes.get("path");
        String messageFound = (String) errorAttributes.get("message");
        String message = "", trace;
        if (!StringUtils.isEmpty(path)) {
            message = String.format("Requested path %s with result %s", path, messageFound);
        }
        trace = (String) errorAttributes.get("trace");
        if (!StringUtils.isEmpty(trace)) {
            message += String.format(" and trace %s", trace);
        }
        throw new BaseException(ErrorCode.SYSTEM_ERROR, message);
    }
}
